import React, {useState} from 'react'
import { useDispatch, useSelector } from 'react-redux';
import { selectAllAuthors } from './authorsSlice';
import { addNewPost } from './postsSlices';

export const AddPostForm = () => {
  const [title, setTitle] = useState('');
  const [content, setContent] = useState('');
  const [author, setAuthor] = useState('');
  const [addRequestStatus, setAddRequestStatus] = useState('idle')

  const authors = useSelector(selectAllAuthors)
  const authorsOptions = authors.map(author => (
    <option key={author.id} value={author.id}>
      {author.name}
    </option>
  ))

  const dispatch = useDispatch();

  const onTitleChanged = e => setTitle(e.target.value);
  const onContentChanged = e=> setContent(e.target.value);
  const onAuthorChanged = e => setAuthor(e.target.value);

  const canSave = [title, content, author].every(Boolean) && addRequestStatus === 'idle'

  const onSavePostClicked = async () => {
    if (canSave) {
      try {
        setAddRequestStatus('pending')
        await dispatch(addNewPost({title, content, user: author})).unwrap()
        console.info("successed")
        setTitle('');
        setContent('');
        setAuthor('')
      } catch (error) {
        console.error('Failed to save the post: ', error)
      } finally {
        setAddRequestStatus('idle')
      }
    } else {
      console.info('dddddd')
    }
  }

  return (
    <section>
      <h2>Add a New Post</h2>
      <form>
        <label htmlFor="postTitle">Post Title:</label>
        <input
          type="text"
          id="postTitle"
          name="postTitle"
          value={title}
          onChange={onTitleChanged}
        />
        <label htmlFor="postAuthor">Author:</label>
        <select id="postAuthor" value={author} onChange={onAuthorChanged}>
          <option value=""></option>
          {authorsOptions}
        </select>
        <label htmlFor="postContent">Content:</label>
        <textarea
          id="postContent"
          name="postContent"
          value={content}
          onChange={onContentChanged}
        />
        <button
          type="button"
          onClick={onSavePostClicked}
        >
          Save Post
        </button>
      </form>
    </section>
  )
}